package com.example.qbbcrssreader;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.example.qbbcrssreader.BBCXmlParser.Entry;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";
    private static final String URL = "http://feeds.bbci.co.uk/news/rss.xml";

	ListView list;
    LazyAdapter adapter;
    List<Entry> entries = null;

 	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Reconnect to Wifi, if enabled but disconnected (possible HTC Desire issue)
		WifiManager wifi;
		wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		Log.i(TAG, "Wifi state: " + wifi.getWifiState());
		if (wifi.isWifiEnabled()) {
			wifi.reconnect();  // reconnect, if its already connected, no harm.
		}

		// Start ListView, adapters and listeners
        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this);
        list.setAdapter(adapter);
        list.setOnItemClickListener (itemClickListener);

        // Start the thread to parse the XML and sort the data
        new DownloadXmlTask().execute(URL);
        
//        list.setOverScrollMode(0);

        // Set the listener on the Refresh button
        Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(listener);
	}
	
    @Override
    public void onDestroy()
    {
        list.setAdapter(null);
        super.onDestroy();
    }

    // Refresh button clicked
    public OnClickListener listener=new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            new DownloadXmlTask().execute(URL);
        }
    };

    // ListView item clicked, go to url on external browser
    public OnItemClickListener itemClickListener = new OnItemClickListener() {
    	@Override
    	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    		String url = entries.get(position).link;
    		Uri uri = Uri.parse(url);
    		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    		startActivity(intent);
    	}
    };
    
/*	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}*/

    // The thread that parses the XML and sorts the data
    private class DownloadXmlTask extends AsyncTask<String, Void, String> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
        	// Show a progress dialog to inform that the list is loading
            progressDialog = ProgressDialog.show(MainActivity.this, "", getString(R.string.pDlg_loading));
        }
        
        @Override
        protected String doInBackground(String... urls) {
            try {
                return loadXmlFromNetwork(urls[0]);
            } catch (IOException e) {
                return getResources().getString(R.string.connection_error);
            } catch (XmlPullParserException e) {
                return getResources().getString(R.string.xml_error);
            }
        }

        @Override
        protected void onPostExecute(String result) {
        	progressDialog.dismiss();
        	// Null if there are no errors
        	if (result == null ) {
        		// Load the adapter with the data
        		adapter.loadData(entries);
        		// The following results in the invalidation/redraw of the ListView 
        		adapter.notifyDataSetChanged();
        	}
        	else {
        		// A dialog to explain the errors
        		AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(MainActivity.this);

        		dlgAlert.setMessage(getString(R.string.dlg_error) + result);
        		dlgAlert.setTitle(getString(R.string.dlg_title));
        		dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        		dlgAlert.setCancelable(true);
        		dlgAlert.create().show();
        	}
        }
    }

    // Uploads XML from URL, parses it, and updates the BCC News item entries array.
    private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
        InputStream stream = null;
        BBCXmlParser bbcXmlParser = new BBCXmlParser();

        try {
            stream = downloadUrl(urlString);
            entries = bbcXmlParser.parse(stream);
        } finally {
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            if (stream != null) {
                stream.close();
            }
        }
        return null;
    }

    // Given a string representation of a URL, sets up a connection and gets
    // an input stream.
    private InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }
}
